//package com.md.infrastructure.config;
//
//import com.md.client.service.AuthenticationClientService;
//import com.md.model.po.Apis;
//import com.md.model.po.Users;
//import com.md.model.system.CommonResult;
//import com.md.util.DateUtils;
//import com.md.util.EncryptionUtils;
//import com.md.util.ObjectUtil;
//import com.md.util.StringUtil;
//import com.md.value.constants.ServerContext;
//import com.md.value.constants.ServerContextConstants;
//import com.md.value.enums.AuthEnum;
//import io.jsonwebtoken.Claims;
//import lombok.NonNull;
//import lombok.RequiredArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.core.Ordered;
//import org.springframework.util.ObjectUtils;
//import org.springframework.web.filter.OncePerRequestFilter;
//
//import javax.servlet.FilterChain;
//import javax.servlet.ServletException;
//import javax.servlet.annotation.WebFilter;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//import java.time.LocalDateTime;
//import java.util.Optional;
//
///**
// * 鉴权的过滤器
// *
// * @author 刘骄阳
// * 2022-04-06 17:14
// */
//@WebFilter({"/logs/*", "/api/*", "/role/*", "/users/*", "/goods-type/*"})
//@Slf4j
//@RequiredArgsConstructor
//public class MacFilter extends OncePerRequestFilter implements Ordered {
//  private final AuthenticationClientService authenticationClientService;
//
//  /**
//   * Same contract as for {@code doFilter}, but guaranteed to be
//   * just invoked once per request within a single request thread.
//   * See {@link #shouldNotFilterAsyncDispatch()} for details.
//   * <p>Provides HttpServletRequest and HttpServletResponse arguments instead of the
//   * default ServletRequest and ServletResponse ones.
//   *
//   * @param request     request
//   * @param response    response
//   * @param filterChain filterChain
//   */
//  @Override
//  protected void doFilterInternal(final @NonNull HttpServletRequest request,
//                                  final @NonNull HttpServletResponse response,
//                                  final @NonNull FilterChain filterChain) throws ServletException, IOException {
//    log.info("鉴权过滤器执行~~~");
//    // 判断是否应用内调用
//    Object parentId = ServerContext.get(ServerContextConstants.PARENT_ID);
//    if (ObjectUtils.isEmpty(parentId)) {
//      filterChain.doFilter(request, response);
//      ServerContext.clear();
//      return;
//    }
//
//    //  判断接口是否需要权限
//    String contextPath = request.getRequestURI();
//    // 不需要token直接放行
//    Apis apis = authenticationClientService.queryApiInfo(contextPath);
//    AuthEnum authEnum = Optional.ofNullable(apis).map(Apis::getAuth).map(AuthEnum::of).orElse(AuthEnum.OPEN);
//    // 获取token
//    String token = request.getHeader(ServerContextConstants.TOKEN);
//    //  校验是否需要token
//    switch (authEnum) {
//      case NEED:
//        if (StringUtils.isBlank(token)) {
//          // 没有token提示去登录
//          errorEnum(response, ErrorEnum.UNAUTHORIZED);
//          return;
//        }
//        break;
//      case PROHIBIT:
//        errorEnum(response, ErrorEnum.PERMISSION);
//        return;
//      default:
//        break;
//    }
//    if (StringUtils.isNotBlank(token)) {
//      // 如果token不存在,返回需要token
//      Claims claims = EncryptionUtils.jwtDecrypt(token);
//      log.info("用户信息为: {}", StringUtil.objectToJson(claims));
//      String userJson = String.valueOf(claims.get("users"));
//      Users users = StringUtil.jsonToObject(userJson, Users.class);
//      if (!ObjectUtils.isEmpty(users)) {
//        // 查询用户信息
//        Users user = authenticationClientService.queryUsersInfo(users.getId());
//        LocalDateTime frozen = user.getFrozen();
//        LocalDateTime now = LocalDateTime.now();
//        if (!ObjectUtils.isEmpty(frozen) && frozen.isAfter(now)) {
//          errorEnum(response, ErrorEnum.USER_UNAVAILABLE, DateUtils.timeDifference(frozen, now));
//          return;
//        }
//
//        // 判断是否需要校验权限
//        if (AuthEnum.NEED.equals(authEnum)) {
//          // 拿到用户信息,判断用户角色是否拥有权限
//          Boolean hasAuth = authenticationClientService.queryHasAuth(apis.getId(), user.getRoleId());
//          if (ObjectUtil.unEquals(true, hasAuth)) {
//            errorEnum(response, ErrorEnum.PERMISSION);
//            return;
//          }
//        }
//        ServerContext.put(ServerContextConstants.USER_ID, user.getId());
//      }
//    }
//
//    // 获取访问地址
//    filterChain.doFilter(request, response);
//    ServerContext.clear();
//  }
//
//  /**
//   * 获取此对象的顺序值,值越低优先级越高
//   *
//   * @return the order value
//   */
//  @Override
//  public int getOrder() {
//    return 9;
//  }
//
//  public void errorEnum(final HttpServletResponse response,
//                        final ErrorEnum errorEnum,
//                        final Object... obj) throws IOException {
//    response.setCharacterEncoding("UTF-8");
//    response.setContentType("application/json");
//    response.getWriter().println(CommonResult.error(errorEnum, obj));
//    response.getWriter().flush();
//  }
//}
